# coding: UTF-8
# Filename : login_api.py
# Company : imedia
# Author : rose
# -*-coding:utf-8 -*-
from api.common.common import *
from api.common import mysql,log,utils,httputils
import time
import user_data_model
from api.points_record import points_record_manage
'''http://api.imedia.com/app/user/login/'''
#验证用户返回主键
def get_login_id(mobile, pwd, cus_id):
    sql = '''
    select tb1.id from `user` tb1, user_cus_list tb2
    where tb1.id = tb2.user_id
    and tb1.active = '1'
    and tb1.username = %s
    and tb2.password = %s
    and tb2.cus_id = %s
    '''
    mobile_int = int(mobile)
    md5_pwd = utils.getMD5(pwd)
    param = [mobile_int, md5_pwd, cus_id]
    user_obj = mysql.get(sql, param)
    user_id = 0
    if user_obj != None and len(user_obj) != 0:
        user_id = user_obj[0]
    return user_id

#登陆逻辑
def login(request):
    httputils.footprint(request)
    
    #通信验证
    if validate(request):
        log.print_error_log('warning:user_api.py->method_register验证失败')
        return validate(request)
    
    #--------------登陆逻辑--------------------
    mobile = httputils.post(request, 'mobile')
    pwd = httputils.post(request, 'pwd')
    cus_id = httputils.post(request, 'cus_id')
    if not utils.is_num(cus_id): cus_id = 0
    if not utils.is_num(mobile): mobile = 0
    user_id = get_login_id(mobile, pwd, cus_id)
    if user_id != 0 :
        #首先增加积分
        (flag, scores) = points_record_manage.login_record(user_id, cus_id)
        user_id_str = str(user_id)
        success = user_data_model.imedia_body
        success = success.replace('{uid}', user_id_str).replace('{success}', '1')
        return response(success)
    else:
        login_error = user_data_model.login_error_model
        return response(login_error)
    
